<?php
namespace Admin\Model;
use \Think\Model\ViewModel;
class UserModel extends ViewModel{

    public $tableName = "user";

    public $viewFields;

    //自动完成
    protected $_auto = array(
        //array(填充字段,填充内容,[填充条件,附加规则])
    );

    //表单验证
    protected $_validate = array(
        //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
        array('username', 'require', '帐号不能为空'),
        array('username','','帐号已经存在', 0, 'unique', 3),
        array('password', '5,20', '密码不能小于5位 ', 2, 'length'),
        array('password', 'require', '密码不能为空', 0, 'regex', 1),
        array('c_password','password','确认密码不正确',0,'confirm'),
    );

    public function __construct() {
        parent::__construct();
        $prefix = C('DB_PREFIX');
        $this->viewFields = array(
            'user'=>array('_table'=>$prefix.'user', "_type" => 'INNER'),
            'role'=>array('_table'=>$prefix.'role', '_on'=>'user.rid=role.rid'),
        );
    }

    /**
     * 删除用户
     * @param int $uid 用户uid
     * @return mixed
     */
    public function delUser($uid)
    {
        $uid = is_array($uid) ? $uid : explode(',',$uid);
        if (M($this->tableName)->where(array('uid'=>['IN',$uid]))->delete()) {
            return true;
        } else {
            $this->error = '删除失败';
        }
    }

    /**
     * 修改用户
     */
    public function editUser($post = array())
    {
        $data = array();
        $post = $post ? $post : $_POST;
        $fields = M($this->tableName)->getDbFields();
        if ($uid = $post['uid']) {
            if($this->autoValidation($post,2)) {
                //没有添加密码时删除密码数据
                if (isset($post['password']) && empty($post['password'])) {
                    unset($post['password']);
                } else {
                    if(isset($post['password']) && !empty($post['password'])) {
                        $code = $this->getUserCode();
                        $post['code'] = $code;
                        $post['password'] = $this->hashPassword($post['password'], $code);
                    }
                }
                isset($post['status']) AND $post['status'] = intval($post['status']);
                isset($post['credits']) AND $post['credits'] = intval($post['credits']);
                foreach($post as $field=>$val) {
                    if(in_array($field,$fields)) {
                        $data['user.'.$field] = $val;
                    }
                }
                if (false !== $this->where(array('user.uid'=>$uid))->save($data)) {
                    return true;
                } else {
                    $this->error = '修改失败';
                }
            }
        } else {
            $this->error = '参数错误';
        }
    }

    /**
     * 添加帐号
     */
    public function addUser($post = array())
    {
        $data = array();
        $post = $post ? $post : $_POST;
        $mod = M($this->tableName);
        $fields = $mod->getDbFields();
        if($this->autoValidation($post,1)) {
            $post['nickname'] = $post['username'];
            $post['regtime'] = time();
            $post['logintime'] = time();
            $post['regip'] = get_client_ip();
            $post['lastip'] = get_client_ip();
            $post['status'] = isset($post['status']) ? intval($post['status']) : 0;
            $post['credits'] = isset($post['credits']) ? intval($post['credits']) : 0;
            $code = $this->getUserCode();
            $post['code'] = $code;
            $post['password'] = $this->hashPassword($post['password'], $code);
            foreach($post as $field=>$val) {
                if(in_array($field,$fields)) {
                    $data[$field] = $val;
                }
            }
            //保存数据
            if ($uid = $mod->add($data)) {
                return true;
            } else {
                $this->error = '添加失败';
                return false;
            }
        }
    }

    /**
     * 获取用户信息
     * @param int|string $uid 用户名或者用户ID
     * @return boolean|array
     */
    public function getUserInfo($uid, $password = NULL) {
        if (empty($uid)) {
            return false;
        }
        $map = array();
        //判断是uid还是用户名
        if (is_int($uid)) {
            $map['uid'] = $uid;
        } else {
            $map['username'] = $uid;
        }
        $user = $this->where($map)->find();
        if (empty($user)) {
            return false;
        }
        //密码验证
        if (!empty($password) && $this->hashPassword($password, $user['code']) != $user['password']) {
            return false;
        }
        return $user;
    }

    /**
     * 更新登录状态信息
     */
    public function loginState($uid)
    {
        $data = array(
            'uid'       => $uid,
            'logintime' => time(),
            'lastip'    => get_client_ip()
        );
        return $this->save($data);
    }

    /**
     * 对明文密码，进行加密，返回加密后的密文密码
     * @param string $password 明文密码
     * @param string $code 认证码
     * @return string 密文密码
     */
    public function hashPassword($password, $code = "") {
        return md5($password . md5($code));
    }

    /**
     * 修改密码
     * @param int $uid 用户ID
     * @param string $newPass 新密码
     * @param string $password 旧密码
     * @return boolean
     */
    public function changePassword($uid, $newPass, $password = NULL) {
        $userInfo = $this->getUserInfo((int) $uid, $password);
        if (empty($userInfo)) {
            $this->error = '旧密码不正确或者该用户不存在！';
            return false;
        }
        $code = $this->getUserCode();
        $status = $this->where(array('uid' => $userInfo['uid']))->save(array('password' => $this->hashPassword($newPass, $code), 'code' => $code));
        return $status !== false ? true : false;
    }

    /**
     * 获取用户密码加密key
     * @return string
     */
    public function getUserCode()
    {
        return substr(md5(C("AUTH_KEY") . mt_rand(1, 1000) . time() . C('AUTH_KEY')), 0, 10);
    }
}